package com.csg.ses.service.ses.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csg.ses.common.utils.CommonUtil;
import com.csg.ses.common.utils.MybatisPlusUtil;
import com.csg.ses.common.utils.SnowFlakeUtil;
import com.csg.ses.dao.ses.SysRoleAccountsDao;
import com.csg.ses.dao.ses.SysRoleRightDao;
import com.csg.ses.dao.ses.SysRoleTypeDao;
import com.csg.ses.dao.ses.SysRolesDao;
import com.csg.ses.entity.ses.SysRoleRightEntity;
import com.csg.ses.entity.ses.SysRoleTypeEntity;
import com.csg.ses.entity.ses.SysRolesEntity;
import com.csg.ses.service.ses.SysRolesService;
import com.csg.ses.vo.common.CascadeDropData;
import com.csg.ses.vo.common.IdListVo;
import com.csg.ses.vo.common.Result;
import com.csg.ses.vo.common.ResultStatus;
import com.csg.ses.vo.list.RoleVo;
import com.csg.ses.vo.login.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色信息
 * @author wangjun
 * @date 2020/11/16
 */
@Service
@RequiredArgsConstructor
public class SysRolesServiceImpl extends ServiceImpl<SysRolesDao, SysRolesEntity> implements SysRolesService {
    private final SysRolesDao sysRolesDao;
    private final SysRoleAccountsDao accountsDao;
    private final SysRoleRightDao rightDao;
    private final SysRoleTypeDao roleTypeDao;

    @Override
    public Result retrieve(SysRolesEntity role, Long current, Long size) {
        try {
            Page<SysRolesEntity> page = MybatisPlusUtil.initPage(current, size, true);
            QueryWrapper<SysRolesEntity> qw = new QueryWrapper();
            if (!CommonUtil.isEmpty(role.getRoleName())) {
                qw.like("role_name", role.getRoleName());
            }
            if (!CommonUtil.isEmpty(role.getRoleTypeId())) {
                qw.eq("role_type_id", role.getRoleTypeId());
            }
            if (!CommonUtil.isEmpty(role.getUseFlag())) {
                qw.eq("use_flag", role.getUseFlag());
            }
            qw.orderByAsc("role_type_id", "role_id");
            return new Result(sysRolesDao.retrieve(page, qw), ResultStatus.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultStatus.FAILED);
        }
    }

    @Override
    public List<String> getUserRoles(String loginId) {
        return sysRolesDao.getUserRoles(loginId);
    }

    @Override
    @Transactional
    public Result del(IdListVo idList) {
        try {
            if (idList != null && idList.getIdList().size() > 0) {
                List<String> roleList = idList.getIdList();
                Integer account = accountsDao.countByRoleIds(roleList);
                Integer right = rightDao.countByRoleIds(roleList);
                String res = "";
                if (account > 0 && right > 0) {
                    res += "所选角色已关联账户和权限控制对象，";
                } else if (account > 0 && right == 0) {
                    res += "所选角色已关联账户，";
                } else if (account == 0 && right > 0) {
                    res += "所选角色已关联权限对象，";
                }
                if (!"".equals(res)) {
                    return new Result(res + "不可删除！", ResultStatus.BIZ_FAILED);
                } else {
                    int num = sysRolesDao.deleteBatchIds(roleList);
                    return new Result(num + "条记录删除成功！", ResultStatus.SUCCESS);
                }
            } else {
                return new Result("未指定需要删除的记录！", ResultStatus.BIZ_FAILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    public Result getById(String id) {
        if (!CommonUtil.isEmpty(id)) {
            return new Result(sysRolesDao.selectById(id), ResultStatus.SUCCESS);
        } else {
            throw new RuntimeException("id不能为空！");
        }
    }

    @Override
    @Transactional
    public String save(RoleVo roleVo) {
        try {
            if (roleVo != null && roleVo.getRoleList().size() > 0) {
                for (SysRolesEntity role : roleVo.getRoleList()) {
                    role.setModifyTime(new Timestamp(System.currentTimeMillis()));
                    role.setModifiedBy(UserContext.getUserView().getLoginCode());
                    if (!CommonUtil.isEmpty(role.getRoleId())) {    //更新
                        sysRolesDao.updateById(role);
                    } else {    //新增
                        role.setRoleId(getNextId().toString());
                        role.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        role.setCreatedBy(UserContext.getUserView().getLoginCode());
                        role.setUseFlag("Y");
                        sysRolesDao.insert(role);
                    }
                }
                return "保存成功！";
            } else {
                return "未传入需要保存的记录！";
            }
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    @Override
    public Result dropData() {
        try {
            List<Map<String, String>> dropList = new ArrayList<>();
            QueryWrapper<SysRolesEntity> qw = new QueryWrapper();
            qw.eq("use_flag", "Y");
            qw.orderByAsc("role_type_id", "role_id");
            List<SysRolesEntity> result = sysRolesDao.selectList(qw);
            if (result != null && result.size() > 0) {
                for (SysRolesEntity role : result) {
                    Map<String, String> map = new LinkedHashMap<String, String>();
                    map.put("value", role.getRoleId());
                    map.put("label", role.getRoleName());
                    dropList.add(map);
                }
            }
            return new Result(dropList, ResultStatus.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultStatus.FAILED);
        }
    }

    @Override
    public Result cascadeDrop() {
        try {
            /**角色类型*/
            QueryWrapper<SysRoleTypeEntity> roleTypeQuery = new QueryWrapper();
            roleTypeQuery.eq("use_flag", "Y");
            roleTypeQuery.orderByAsc("role_type_id");
            List<SysRoleTypeEntity> roleTypeList = roleTypeDao.selectList(roleTypeQuery);

            /**角色信息*/
            QueryWrapper<SysRolesEntity> qw = new QueryWrapper();
            qw.eq("use_flag", "Y");
            qw.orderByAsc("role_type_id", "role_id");
            List<SysRolesEntity> roleList = sysRolesDao.selectList(qw);

            List<CascadeDropData> result = this.dealCascadeDrop(roleTypeList, roleList);
            return new Result(result, ResultStatus.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    public Integer getNextId() {
        return sysRolesDao.getNextId();
    }


    @Override
    public boolean saveOredit(SysRolesEntity sysRolesEntity) {
        try {
            sysRolesEntity.setModifyTime(new Timestamp(System.currentTimeMillis()));
            sysRolesEntity.setModifiedBy(UserContext.getUserView().getLoginCode());
            //修改
            if (sysRolesEntity.getRoleId()!=null) {
                List<String> idList=new ArrayList<>();
                idList.add(sysRolesEntity.getRoleId()+"");
                //先删除所有权限记录
                rightDao.deleteByroleId(idList);
                //再添加
                String[] privstrlist = sysRolesEntity.getRolePrivstr().split(",");
                if(privstrlist.length>0) {
                    for (String privstr : privstrlist) {
                        SysRoleRightEntity roleright = new SysRoleRightEntity();
                        roleright.setId(getNextrolerRightId() + "");
                        roleright.setRoleId(sysRolesEntity.getRoleId() + "");
                        roleright.setObjectType("MENU_ITEM");
                        roleright.setObjectId(privstr);
                        roleright.setPermission("Y");
                        roleright.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        roleright.setCreatedBy(UserContext.getUserView().getLoginCode());
                        roleright.setModifyTime(new Timestamp(System.currentTimeMillis()));
                        roleright.setModifiedBy(UserContext.getUserView().getLoginCode());
                        rightDao.insert(roleright);
                    }
                }
                sysRolesDao.updateById(sysRolesEntity);
            }
            //添加
            else
                {
                    //sys_roles表
                    sysRolesEntity.setRoleId(getNextId()+"");
                    sysRolesEntity.setRoleTypeId("1");
                    sysRolesEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    sysRolesEntity.setCreatedBy(UserContext.getUserView().getLoginCode());
                    sysRolesEntity.setUseFlag("Y");
                    sysRolesDao.deleteById(sysRolesEntity.getRoleId());
                    sysRolesDao.insert(sysRolesEntity);

                    //sys_roleRight表
                    String[] privstrlist=sysRolesEntity.getRolePrivstr().split(",");
                    if(privstrlist.length>0) {
                        for (String privstr : privstrlist) {
                            SysRoleRightEntity roleright = new SysRoleRightEntity();
                            roleright.setId(getNextrolerRightId() + "");
                            roleright.setRoleId(sysRolesEntity.getRoleId() + "");
                            roleright.setObjectType("MENU_ITEM");
                            roleright.setObjectId(privstr);
                            roleright.setPermission("Y");
                            roleright.setCreateTime(new Timestamp(System.currentTimeMillis()));
                            roleright.setCreatedBy(UserContext.getUserView().getLoginCode());
                            roleright.setModifyTime(new Timestamp(System.currentTimeMillis()));
                            roleright.setModifiedBy(UserContext.getUserView().getLoginCode());
                            rightDao.insert(roleright);
                        }
                    }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 处理级联下拉
     * @param roleTypeList
     * @param roleList
     * @return
     */
    public List<CascadeDropData> dealCascadeDrop(List<SysRoleTypeEntity> roleTypeList, List<SysRolesEntity> roleList) {
        try {
            List<CascadeDropData> result = new ArrayList<CascadeDropData>();
            for (SysRoleTypeEntity type : roleTypeList) {
                CascadeDropData parent = new CascadeDropData();
                parent.setValue(type.getRoleTypeId());
                parent.setLabel(type.getRoleTypeName());
                parent.setDropType("ROLE_TYPE");

                List<CascadeDropData> children = new ArrayList<CascadeDropData>();
                for (SysRolesEntity role : roleList) {
                    CascadeDropData child = new CascadeDropData();
                    if (role.getRoleTypeId().equals(type.getRoleTypeId())) {
                        child.setValue(role.getRoleId());
                        child.setLabel(role.getRoleName());
                        child.setDropType("ROLE");
                        child.setChildren(null);
                        children.add(child);
                    }
                }
                parent.setChildren(children.size() > 0 ? children : null);
                result.add(parent);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
    @Override
    public Integer getNextrolerRightId() {
        return sysRolesDao.getNextrolerRightId();
    }
}